package com.zsd.android.okhttplib.chain;

import com.zsd.android.okhttplib.OkHttpClient;
import com.zsd.android.okhttplib.RealCall;
import com.zsd.android.okhttplib.Response;

import java.io.IOException;

/**
 * 重试拦截器
 */
public class ReRequestInterceptor implements Interceptor {

    @Override
    public Response doNext(Chain chain) throws IOException {
        ChainManager manager = (ChainManager) chain;
        RealCall call = manager.getCall();
        OkHttpClient client = call.getClient();

        IOException ioException = null;

        int recount = client.getRecount();
        if (recount != 0) {
            for (int i = 0; i < recount; i++) {
                try {
                    //如果没有异常，循环结束
                    Response response = chain.getResponse(manager.getRequest());
                    return response;
                } catch (IOException e) {
                    ioException = e;
                }
            }
        }
        throw ioException;
    }
}
